package com.qs.questionnairesurveysystem.controller;

import com.qs.questionnairesurveysystem.dto.Report;
import com.qs.questionnairesurveysystem.dto.Result;
import com.qs.questionnairesurveysystem.entity.Answer;
import com.qs.questionnairesurveysystem.entity.Survey;
import com.qs.questionnairesurveysystem.entity.User;
import com.qs.questionnairesurveysystem.service.AnswerService;
import com.qs.questionnairesurveysystem.service.SurveyService;
import com.qs.questionnairesurveysystem.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/surveys")
@Api(tags = "Survey Controller")
public class SurveyController {

    @Autowired
    private SurveyService surveyService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "Create a new survey", notes = "Creates a new survey in the system.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Survey created successfully."),
            @ApiResponse(code = 400, message = "Invalid input data.")
    })
    @PostMapping
    public Result<Survey> createSurvey(@RequestBody Survey survey) {
        surveyService.createSurvey(survey);
        return Result.success(survey);
    }

    @ApiOperation(value = "Update an existing survey", notes = "Updates an existing survey in the system.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Survey updated successfully."),
            @ApiResponse(code = 404, message = "Survey not found.")
    })
    @PutMapping("/{surveyId}")
    public Result<Survey> updateSurvey(@PathVariable Long surveyId, @RequestBody Survey survey) {
        survey.setSurveyId(surveyId);
        surveyService.updateSurvey(survey);
        return Result.success(survey);
    }

    @ApiOperation(value = "Delete a survey", notes = "Deletes a survey from the system.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Survey deleted successfully."),
            @ApiResponse(code = 404, message = "Survey not found.")
    })
    @DeleteMapping("/{surveyId}")
    public Result<String> deleteSurvey(@PathVariable Long surveyId) {
        surveyService.deleteSurvey(surveyId);
        return Result.success("Survey deleted successfully.");
    }

    @ApiOperation(value = "Get a specific survey by ID", notes = "Fetches a survey by its ID.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Survey retrieved successfully."),
            @ApiResponse(code = 404, message = "Survey not found.")
    })
    @GetMapping("/{surveyId}")
    public Result<Survey> getSurveyById(@PathVariable Long surveyId) {
        Survey survey = surveyService.getSurveyById(surveyId);
        return survey != null ? Result.success(survey) : Result.error("not found", 404);
    }


    @GetMapping
    public Result<List<Survey>> getAllSurveys() {
        List<Survey> surveys = surveyService.getAllSurveys();
        return Result.success(surveys);
    }


    @GetMapping("/end")
    public Result<List<Survey>> getEndSurveys() {
        List<Survey> surveys = surveyService.getEndSurveys();
        return Result.success(surveys);
    }

    @GetMapping("/record/{uid}")
    public Result<List<Survey>> getEndSurveysRecordUid(@PathVariable Long uid) {
        List<Survey> surveys = surveyService.getEndSurveysRecord(uid);
        return Result.success(surveys);
    }

    @ApiOperation(value = "Get surveys by creator ID", notes = "Fetches all surveys created by a specific creator.")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Surveys retrieved successfully.")
    })

    @GetMapping("/creator/{creatorId}")
    public Result<List<Survey>> getSurveysByCreatorId(@PathVariable Long creatorId) {
        List<Survey> surveys = surveyService.getSurveysByCreatorId(creatorId);
        return Result.success(surveys);
    }

    @GetMapping("/report/{surveyId}")
    public Result<Report> getSurveysReport(@PathVariable Long surveyId) {
        Report res = new Report();
        List<Answer> answers = answerService.getAnswersBySurveyId(surveyId);
        Map<String, Integer> counts = new HashMap<>();
        Map<Long, User> users = new HashMap<>();
        answers.forEach(answer -> {
            User user;
            if(users.get(answer.getRespondentId()) != null) {
                user = users.get(answer.getRespondentId());
                return;
            }else{
                user = userService.getUserById(answer.getRespondentId());
                users.put(answer.getRespondentId(), user);
            }
            if(user.getGender().equals("male")) {
                res.setMen(res.getMen() + 1);
            }else{
                res.setWomen(res.getWomen() + 1);
            }
            counts.merge(user.getRegion(), 1, Integer::sum);
        });

        // 将 counts 按照 value 排序，获取前 5 个（如果不足 5 个则获取全部）
        List<Map.Entry<String, Integer>> sortedCounts = counts.entrySet()
                .stream()
                .sorted((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()))  // 按照 value 降序排序
                .limit(5)  // 只取前 5 个
                .toList();

        sortedCounts.forEach(item -> {
           res.addArea(item.getKey(), item.getValue());
        });

        return Result.success(res);
    }

}
